import axios from 'axios'
import { Message } from 'element-ui'

const service = axios.create({
  baseURL: '',
  timeout: 300000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  }
})
// 请求拦截器
service.interceptors.request.use(
  config => {
    if (config.isExport) {
      config.responseType = 'arraybuffer'
    }
    if (config.method === 'get') {
      config.params = config.data
    }
    return config
  },
  error => {
    Promise.reject(error)
  }
)
// 响应拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = '请求错误'
          break
        case 401:
          error.message = '您还未登录或者登录超时'
          break
        case 403:
          error.message = '拒绝访问'
          break
        case 404:
          error.message = `请求地址出错: ${error.response.config.url}`
          break
        case 408:
          error.message = '请求超时'
          break
        case 500:
          error.message = '服务器内部错误'
          break
        case 501:
          error.message = '服务未实现'
          break
        case 502:
          error.message = '网关错误'
          break
        case 503:
          error.message = '服务不可用'
          break
        case 504:
          error.message = '网关超时'
          break
        case 505:
          error.message = 'HTTP版本不受支持'
          break
        default:
          break
      }
    }
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
